﻿using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using HossMvp.Core;
using HossMvp.WinForms;

namespace Sample.Views
{
    public class AboutView : AbstractView, IDisposable
    {
        private readonly EventHandler idleCheck;

        public AboutView(AbstractViewManager manager, string name, IContentProvider contents)
            : base(manager, name, contents)
        {
            this.BindCommands();
            this.idleCheck = (s, a) => this.Manager.Presenter.CommandProcessor.Enable();
            Application.Idle += this.idleCheck;
        }

        public void Dispose()
        {
            Application.Idle -= this.idleCheck;
        }

        protected override void BindCommands()
        {
            // Close
            this.Manager.GetCommand("Close").Bind(this.Contents.Get<IComponent>("buttonClose"));
        }

        public class AboutViewContentProvider : WinFormsContentProvider
        {
            public AboutViewContentProvider(Form form = null)
                : base(form, new NameDecorator("About"))
            {
                //this.RegisterAction(this.Decorator.NameOf<AboutViewContentProvider>(f => f.Show), this.Show);
                //this.RegisterAction(this.Decorator.NameOf<AboutViewContentProvider>(f => f.Close), this.Close);
                this.RegisterActions();
            }

            private ActionResult Show(ActionContext context)
            {
                var parent = context.Get<Form>("parent");
                
                // result makes compiler "happy"
                //var result = this.ShowDialogAsync(parent);
            
                this.Form.ShowDialog(parent);
                return null;
            }

            private ActionResult Close(ActionContext context)
            {
                this.Form.Close();
                return null;
            }

            // TODO: causes cross-thread exception, fix it!
            private async Task<DialogResult> ShowDialogAsync(Form parent = null)
            {
                return await Task.Run(() => this.Form.ShowDialog(parent));
            }
        }
    }
}
